<?php

/**
 * Description of ReportqueueController
 *
 */
class ReportqueueController extends Zend_Controller_Action {

    /*
     * Author: Omar 
     */
    public function addAction() {

        $json = new Zend_Json();
        $encodedParams = $json->encode($_GET);
        $recordTable = ReportQueueTable::getInstance();
        $recordTable->addToQueue($encodedParams);
        $this->_redirect("/reportqueue/show");
    }

    /*
     * Author: Omar
     * The showAction renders its view,show.phtml,which draws the grid and fill
     * the data store from the dataAction.
     */

    public function showAction() {

    }

    /*
     * Author: Omar
     */
    public function dataAction() {

        $this->_helper->layout()->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender(true);
        $reportTable = ReportQueueTable::getInstance();
        $ranges = explode(',', substr($_SERVER['HTTP_RANGE'], 6));
        foreach ($ranges as $range) {
        $parts = explode('-', $range);
        $start = $parts[0]; // If this is empty, this should be 0.
        $end = $parts[1]; // If this is empty or greater than than filelength - 1, this should be filelength - 1.
    }
        $requests = $reportTable->getQueue($start,$end);
        $json = new Zend_Json();
        $result = array();
        foreach ($requests as $key => $value) {
            $result[$key]['id'] = $value['id'];
            $result[$key]['created_at'] = $value['created_at'];
            if ($value['progress'] != "Done") {
                $result[$key]['progress'] = $value['progress'];
                $result[$key]['updated_at'] = "Not completed yet";
            } else {
                $result[$key]['progress'] = "Download";
                $result[$key]['updated_at'] = $value['updated_at'];
            }

            $criterias = $json->decode($value['criteria_json']);

            if ($criterias['status'] == '0') {
                $status = "Any";
            } else {
                $status = $criterias['status'];
            }

            if ($criterias['createdBy'] == '0') {
                $createdBy = "Any";
            } else {
                $createdBy = Doctrine_Query::create()->select('name')
                                ->from('Account')->where('id=?', $criterias['createdBy'])
                                ->execute(array(), Doctrine::HYDRATE_SINGLE_SCALAR);
            }

            if ($criterias['authorization'] == '0') {
                $authorization = "Any";
            } else {
                $authorization = $criterias['authorization'];
            }

            if ($criterias['supervisor'] == '0') {
                $supervisor = "Any";
            } else {
                $supervisor = Doctrine_Query::create()->select('name')
                                ->from('Account')->where('id=?', $criterias['supervisor'])
                                ->execute(array(), Doctrine::HYDRATE_SINGLE_SCALAR);
            }

            if ($criterias['publisher'] == '0') {
                $publisher = "Any";
            } else {
                $publisher = Doctrine_Query::create()->select('publisherName')
                                ->from('Publisher')->where('id=?', $criterias['publisher'])
                                ->execute(array(), Doctrine::HYDRATE_SINGLE_SCALAR);
            }

            if ($criterias['from'] == '') {
                $from = "Any";
            } else {
                $from = $criterias['from'];
            }

            if ($criterias['to'] == '') {
                $to = "Any";
            } else {
                $to = $criterias['to'];
            }
            $dcriteria = "Status:$status  Created by:$createdBy  Authorization:$authorization  Supervisor:$supervisor
            Publisher:$publisher  from:$from  to:$to";
            $result[$key]['criteria'] = $dcriteria;
        }
        $jsonData = $json->encode($result);
                $this->getResponse()
        ->setHttpResponseCode(200)
        ->setHeader("Content-Range", "items ".$start."-".$end."/".$reportTable->getCount())
        ->appendBody($jsonData);
    }

    /*
     * Author: Eman
     * 
     * This function is called by a cron job every 1 minute to watch the progress of the requests in the queue.
     * If no request in progress, then the next request in the queue will be handled.
     * The products matching the criteria of the current request will be retrieved and exported to excel file.
     * 
     */
    public function executeAction() {
        $this->_helper->layout()->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender(true);

        $reportTable = ReportQueueTable::getInstance();
        // Check if there is a request in progress:
        if (!$reportTable->isInProgress()) {
            // Since there is no request in progress,get next request in queue:
            $currentRequest = $reportTable->getOldestRequest();

            // Update the progress status of the request to "In progress"
            $reportTable->updateProgress($currentRequest['id'], 'In progress');

          

            // Get products matching the criteria of this request
            $criteria = Zend_Json::decode($currentRequest['criteria_json']);
            $productTable = RepProductTable::getInstance();
            $query = $productTable->getProduct($criteria);
            $data = $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY);


            // Send Product info to ExportExcel class:
            $export = new Lib_ExportExcel($currentRequest['id'], $data);
            
            $export->init();
           // if ($export->init()) {
                // If excel file created successfully update the progress' status to Done
                $reportTable->updateProgress($currentRequest['id'], 'Done');
           // }
        }
    }

}
